from PIL import ImageGrab, Image
import numpy as np
import cv2
from datetime import datetime
import pandas as pd


def healerCheckOtherBloodBarInGrid(currentMouseBar, HMouse, width):
    # antasya
    # x1 = 472
    # y1 = 375
    # x2 = 590
    # y2 = 543

    WStep = width / 20
    BreakPoint = 0

    redList = []
    greenList = []
    blueList = []
    bigestList = []

    for i in range(0, 20):
        roiLoop = currentMouseBar.crop((WStep*i, 0, WStep*(i+1), HMouse))
        rButton1, gButton1, bButton1 = roiLoop.split()
        rButton1.thumbnail((1, 1))
        redList.append(rButton1.getpixel((0, 0)))
        gButton1.thumbnail((1, 1))
        greenList.append(gButton1.getpixel((0, 0)))
        bButton1.thumbnail((1, 1))
        blueList.append(bButton1.getpixel((0, 0)))

    # 头部和尾部的色差
    ColorMindGapRed = abs((sum(redList[-4:])/4 - sum(redList[0:4])/4)/2)
    ColorMindGapGreen = abs((sum(greenList[-4:])/4 - sum(greenList[0:4])/4)/2)
    ColorMindGapBlue = abs((sum(blueList[-4:])/4 - sum(blueList[0:4])/4)/2)
    maxGap = max(ColorMindGapRed, ColorMindGapGreen, ColorMindGapBlue)
    # 头部和尾部的综合平均值
    ColorMindRedAvg = abs((sum(redList[-4:])/4 + sum(redList[0:4])/4)/2)
    ColorMindGreenAvg = abs((sum(greenList[-4:])/4 + sum(greenList[0:4])/4)/2)
    ColorMindBlueAvg = abs((sum(blueList[-4:])/4 + sum(blueList[0:4])/4)/2)

    if ColorMindGapRed == maxGap:
        bigestList = redList.copy()
    elif ColorMindGapGreen == maxGap:
        bigestList = greenList.copy()
    elif ColorMindGapBlue == maxGap:
        bigestList = blueList.copy()
    bigestList.pop()
    # 平均值，撇开右边可能有bufff显示影响整个平均值，统计的时候剔除掉最右边的n个
    midLine = sum(bigestList[0:-1])/len(bigestList[0:-1])
    ColorMindGap = abs((sum(bigestList[-4:])/4 - sum(bigestList[0:4])/4)/2)
    # 起伏差
    if ColorMindGap > 20:
        # 首位有色差的处理
        for j in range(0, 19):
            if bigestList[0] > bigestList[18]:
                #降序数组
                if bigestList[j] < midLine:
                    #print('find:'+str(j))
                    BreakPoint = j
                    break
                else:
                    pass
            else:
                #升序数组
                if bigestList[j] > midLine:
                    #print('find:'+str(j))
                    BreakPoint = j
                    break
                else:
                    pass

    else:
        # 首尾无色差的处理
        if max([ColorMindRedAvg,ColorMindGreenAvg,ColorMindBlueAvg]) < 50:
            # 无色差已经死亡(都是黑色)
            BreakPoint = 0
        else:
            # 无色差满血(都是绿色)
            BreakPoint = 18
    finalPercentage = (BreakPoint + 1)*5
    print('rest:'+str(finalPercentage))

    return finalPercentage


def judgeLevel(df, threshold):
    if df['score'] <= threshold:
        return 1
    else:
        return 0


def PersonNBloods(personNum, all5BarsRoi, HMouse, width, HStep):
    # antasya:将大秘境5人治疗框体
    healerContinuesList = []
    # personNum，一般大秘境横向切分为5个人（我首先把5个血条的party整块的坐标框起来，切分为5个人）
    for j in range(0, personNum):
        rowsNum = j + 0.5
        # 裁剪中间皮带一条
        delta = 6 #上下移动皮带
        currentMouseBar = all5BarsRoi.crop(
            (0, HStep*rowsNum + delta, width, HStep*rowsNum + HMouse + delta))
        # debug:start皮带减得准不准
        currentMouseBar = all5BarsRoi.crop(
            (0, HStep*j, width, HStep*j + HStep))
        currentMouseBar.save(str(j) + '_debug_pidai.jpg')
        # debug:end皮带剪得准不准
        # 每个人的横向一条血条皮带剪程20截
        s = healerCheckOtherBloodBarInGrid(
            currentMouseBar=currentMouseBar, HMouse=currentMouseBar.height, width=width)
        healerContinuesList.append(s)

    df = pd.DataFrame(healerContinuesList, columns=['score'])
    df['danger95'] = df.apply(lambda r: judgeLevel(r, 95), axis=1)
    df['danger90'] = df.apply(lambda r: judgeLevel(r, 90), axis=1)
    df['danger85'] = df.apply(lambda r: judgeLevel(r, 85), axis=1)
    df['danger80'] = df.apply(lambda r: judgeLevel(r, 80), axis=1)
    df['danger70'] = df.apply(lambda r: judgeLevel(r, 70), axis=1)
    df['danger60'] = df.apply(lambda r: judgeLevel(r, 60), axis=1)
    df['danger50'] = df.apply(lambda r: judgeLevel(r, 50), axis=1)
    df['danger40'] = df.apply(lambda r: judgeLevel(r, 40), axis=1)
    df['danger30'] = df.apply(lambda r: judgeLevel(r, 30), axis=1)
    df['danger20'] = df.apply(lambda r: judgeLevel(r, 20), axis=1)
    df['danger10'] = df.apply(lambda r: judgeLevel(r, 10), axis=1)
    print('antasya')
    print(df)
    dict = {
        'avgNumber': sum(healerContinuesList)/len(healerContinuesList),
        'danger95': sum(df['danger95']),
        'danger90': sum(df['danger90']),
        'danger85': sum(df['danger85']),
        'danger80': sum(df['danger80']),
        'danger70': sum(df['danger70']),
        'danger60': sum(df['danger60']),
        'danger50': sum(df['danger50']),
        'danger40': sum(df['danger40']),
        'danger30': sum(df['danger30']),
        'danger20': sum(df['danger20']),
        'danger10': sum(df['danger10'])
    }
    dfdangers = pd.DataFrame.from_dict(
        dict, columns=['numbers'], orient='index')
    dfdangers['type'] = dfdangers.index
    print('final result:')
    print(dfdangers)
    return dfdangers


if __name__ == '__main__':
    # antasya
    x1=698
    y1=426
    x2=809
    y2=577
    # x1=663
    # y1=378
    # x2=724
    # y2=537
    
    # office
    # x1 = 472
    # y1 = 375
    # x2 = 590
    # y2 = 543
    HStep = (y2-y1)/5
    print('单个高度:' + str(HStep))
    HMouse = 8
    width = x2 - x1
    # E:\game\World of Warcraft\_retail_\Screenshots\WoWScrnShot_111822_194009.jpg
    imButton1 = Image.open(
        r'F:\twgame\World of Warcraft\_retail_\Screenshots\WoWScrnShot_120622_013004.jpg')
    all5BarsRoi = imButton1.crop((x1, y1, x2, y2))
    cv2.imshow('debug', np.array(all5BarsRoi))
    cv2.waitKey(0)
    # **************************************debug1**************************************
    print("1111ImageGrab图像抓取，像素识别前时分秒:" +
        datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
    dfdangers = PersonNBloods(
        personNum=5, all5BarsRoi=all5BarsRoi, HMouse=HMouse, width=width, HStep=HStep)
    print("2222ImageGrab图像抓取，像素识别前时分秒:" +
        datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
    print(dfdangers)
    print(dfdangers[dfdangers['type']=='avgNumber'].iloc[0, 0])
    print(dfdangers[dfdangers['type']=='avgNumber']['numbers'].values[0])
    # print(dfdangers[dfdangers['index']=='avgNumber'])
    # **************************************debug2**************************************
    # rowsNum = 0.5
    # currentMouseBar = all5BarsRoi.crop(
    #     (0, HStep*rowsNum-HMouse/2, width, HStep*rowsNum+HMouse/2))
    # print("ImageGrab图像抓取，像素识别前时分秒:" +
    #       datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
    # s = healerCheckOtherBloodBarInGrid(
    #     currentMouseBar=currentMouseBar, HMouse=HMouse, width=width)
    # print('鼠标指向血条框的剩余血量百分比为:' + str(s))
    # print("ImageGrab图像抓取，像素识别前时分秒:" +
    #       datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
